<template>
    <el-container class="container">
        <div class="searchbar" v-if="isMobile">
            <div style="display: flex; justify-content: space-between;">
                <div class="breadcrumb">
                    <el-breadcrumb separator="/">
                        <el-breadcrumb-item :to="{ path: '/' }"><el-icon><House /></el-icon></el-breadcrumb-item>
                        <el-breadcrumb-item :to="{ path: '/browse' }">Browse Cell Line</el-breadcrumb-item>
                    </el-breadcrumb>
                </div>
                <el-button type="primary" style="margin-left: 16px" @click="drawer = true">
                    Search Conditions
                </el-button>
            </div>
            <el-drawer
                v-model="drawer"
                direction="ltr"
                size="50%"
                v-if="drawer"
                >
                <KeepAlive>
                    <SearchColumn 
                        :searchItems="searchItems" 
                        :updateTable="updateTable" 
                        page="ecDNA"
                        />
                </KeepAlive>   
            </el-drawer>
        </div>
        <div class="searchbar" v-else>
            <div class="breadcrumb">
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item :to="{ path: '/' }"><el-icon><House /></el-icon></el-breadcrumb-item>
                    <el-breadcrumb-item :to="{ path: '/browse' }">Browse Cell Line</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <KeepAlive>
                <SearchColumn 
                    :searchItems="searchItems" 
                    :updateTable="updateTable" 
                    page="ecDNA"
                    />
            </KeepAlive>
        </div>
        <div class="table-container">
            <el-table 
                :data="tableData"
                height="600" 
                stripe
                @sort-change="handleSortChange"
            >
                <el-table-column prop="fields.Cellline" label="CellLine" sortable min-width="150">
                    <template #default="scope">
                        <a class="link" @click="checkCelllineDetail(scope.row)">{{ scope.row.fields.Cellline }}</a>
                    </template>
                </el-table-column>
                <el-table-column prop="fields.OncotreeLineage" label="OncotreeLineage" sortable min-width="160"  />
                <el-table-column prop="fields.MajorTumorType" label="MajorTumorType" sortable min-width="160" />
                <!-- <el-table-column prop="fields.OncotreePrimaryDisease" label="OncotreePrimaryDisease" show-overflow-tooltip sortable width="230" /> -->
                <el-table-column prop="fields.Group" label="Group" sortable min-width="130">
                    <template #default="scope">
                        <p v-if="scope.row.fields.Group">{{ scope.row.fields.Group }}</p>
                        <p v-else>{{ scope.row.fields.ECPositive === 'yes' ? 'ecDNA++' : 'ecDNA-' }}</p>
                    </template>
                </el-table-column>
                <el-table-column prop="fields.Gene" label="Gene" sortable min-width="130" >
                    <template #default="scope">
                        <p v-if="scope.row.fields.Gene">{{ scope.row.fields.Gene.replace(",", ";") }}</p>
                    </template>
                </el-table-column>
                <el-table-column prop="fields.FISH" label="FISH" sortable min-width="100" />
                <el-table-column prop="fields.DAPI" label="DAPI" sortable min-width="100" />
                <!-- <el-table-column label="URL" fixed="right" min-width="80" >
                    <template #default="scope">
                        <span v-if="scope.row.fields.url">
                            <a @click="checkUrl(scope.row)">Check</a>
                        </span>
                        <span v-else>
                            <p>No Url</p>
                        </span>
                    </template>
                </el-table-column> -->
            </el-table>
        </div>
        <div class="pagination-container">
            <el-pagination
                v-model:current-page="currentPage"
                :page-size="currentPageSize"
                background
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
    </el-container> 
</template>

<script lang="ts" setup name="Browse">
    import SearchColumn from '@/components/SearchColumn.vue'
    import { onActivated, onBeforeMount, ref, watch } from 'vue';
    import { ElMessage, rowProps } from 'element-plus'
    import { get, post } from '../../axios/api';
    import { useRoute, useRouter } from 'vue-router';
    import { ElLoading } from 'element-plus'


    let tableData = ref([]);
    let total = ref(0)
    let currentPage = ref(1)
    let currentPageSize = ref(10)
    let selectedValues = ref();
    const router = useRouter()
    const route = useRoute()
    let isMobile = ref(window.innerWidth <= 768)
    let sortedProp = ref('FISH')
    let sortedOrder = ref('descending')
    let isSorted = ref(false)
    const drawer = ref(false)

    const initSortedBy = 'FISH'
    const initSortedOrder = 'descending' 
    let loadingInstance:any = null

    let searchItems:any = ref([
        {label: 'Cell Line', value: 'Cellline', options: [], type: 'multi-select'},
        {label: 'Major Tumor Type', value: 'MajorTumorType', options: [], type: 'multi-select'},
        {label: 'OncotreeLineage', value: 'OncotreeLineage', options: [], type: 'multi-select'},
    ])

    async function getData(page: number, page_size: number, params: any, sort_by: any, sort_order: any) {
        let res:any = {}
        let query = {
            page,
            page_size,
            params: params,
            sort_by,
            sort_order
        }
        try {
            res = await post('/get_browse_data/', query)
        } catch (error:any) {
            loadingInstance.close()
            ElMessage({
                message: error,
                type: 'error',
            })
        }
        if (res && res.success) {
            tableData.value = res.list
            currentPage.value = res.page
            total.value = res.total
            loadingInstance.close()
        } else {
            loadingInstance.close()
            ElMessage({
                message: res.msg ? res.msg : "An error occured",
                type: 'error',
            })
        }
    }

    async function handleOption(items: any) {
        const promises: Promise<any>[] = [];
        for (let item of items) {
            // 分为一般情况和tabs情况，tabs情况需要再来一层
            if (item.type === 'tab-multi-select') {
                for (let tab of item.tabs) {
                    promises.push(getOptions(tab, item.tabs, 'tab'));
                }
            } else {
                promises.push(getOptions(item, searchItems, 'single'));
            }
        }
        await Promise.all(promises);
        console.log(items)
        loadingInstance.close()
    }

    async function getOptions(item: any, items: any, type:string) {
        let res:any = {}
        try {
            let queryData = {
                option: item.value, 
                params: selectedValues.value ? selectedValues.value : {},
            }
            res = await post('/get_browse_options/', queryData)
        } catch (error:any) {
            ElMessage({
                message: error,
                type: 'error',
            })
        }
        if (res && res.success) {
            let target:any = {}
            if (type ==='tab') {
                target = items.find((el: any) => el.value === item.value)
            } else {
                target = items.value.find((el: any) => el.value === item.value)
            }
            target.options = res.data
        } else {
            ElMessage({
                message: res.msg ? res.msg : "An error occured",
                type: 'error',
            })
            return
        }
    }
    

    async function handleSortChange(ele:any) {
        loadingInstance = ElLoading.service({fullscreen: true})
        isSorted.value = true
        sortedProp.value = ele.prop.split('.')[1]
        sortedOrder.value = ele.order
        if (selectedValues.value) {
            getData(currentPage.value, currentPageSize.value, selectedValues.value ,sortedProp.value, sortedOrder.value)
        } else {
            getData(currentPage.value, currentPageSize.value, {} ,sortedProp.value, sortedOrder.value)
        }
    }

    async function handleCurrentChange(val: number) {
        currentPage.value = val
        if (isSorted) {
            getData(val, currentPageSize.value, selectedValues.value, sortedProp.value, sortedOrder.value)
        } else {
            getData(val, currentPageSize.value, selectedValues.value, initSortedBy, initSortedOrder)
        }
    }

    async function handleSizeChange(val: number) {
        currentPageSize.value = val
        if (isSorted) {
            getData(currentPage.value, val, selectedValues.value, sortedProp.value, sortedOrder.value)
        } else {
            getData(currentPage.value, val, selectedValues.value, initSortedBy, initSortedOrder)
        }
    }

    function updateTable(val: any) {
        loadingInstance = ElLoading.service({fullscreen: true})
        selectedValues.value = val;
        let query = val
        if (isSorted) {
            getData(currentPage.value, currentPageSize.value, query, sortedProp.value, sortedOrder.value)
        } else {
            getData(currentPage.value, currentPageSize.value, query, initSortedBy, initSortedOrder)
        }
    }

    function checkCelllineDetail(row: any) {
        router.push({
            name: 'browseDetail',
            params: {
                Cellline: row.fields.Cellline,
                uuid: row.pk
            }
        })
    }

    function checkUrl(row: any) {
        let url = ''
        if (row.fields.url.includes(',')) {
            url = row.fields.url.split(',')[0]
        } else {
            url = row.fields.url
        }
        window.open(url, '_blank')
    }

    watch(drawer, (newValue:any) => {
        if (newValue) {
            handleOption(searchItems.value)
        }
    }, {deep: true})

    onBeforeMount(() => {
        loadingInstance = ElLoading.service({fullscreen: true})
        handleOption(searchItems.value)
        getData(currentPage.value, currentPageSize.value, {}, initSortedBy, initSortedOrder)
    })

</script>

<style lang="scss" scoped>
    .breadcrumb {
        margin: 8px 0;
    }

    .table-container {
        width: 100%;
        margin: 10px 0px;
        display: flex;
        justify-content: center;
        border-radius: 4px;
        background-color: white;
    }
    
    :deep(.el-table)  {
        border-radius: 4px;
    }

    .pagination-container {
        margin: 20px 10px;
        display: flex;
        justify-content: center;
    }
    .link {
        cursor: pointer;
    }

    a {
        color: dodgerblue
    }

    a:hover {
        color: rgb(24, 188, 146);
    }
    
    .container {
        width: 100%;
        display: flex;
        flex-direction: column;
    }

    @media screen and (max-width: 768px) {
        .container {
            width: 100%;
            display: flex;
            flex-wrap: wrap;
        }
    }

    .searchbar {
        width: 100%;
        display: block;
    }
</style>